<template>
  <div id="user" v-if="currentLoginUser">
    <van-card
        :title="currentLoginUser?.username"
        :thumb="currentLoginUser?.avatarUrl"
        style="font-size: medium; margin-top: 5px"
    >
      <template #tags>
        <div style="font-size: small; margin-top: 10px">个人描述：{{ currentLoginUser?.profile }}</div>
        <span style="font-size: small">我的标签：</span>
        <van-tag v-for="tag in JSON.parse(currentLoginUser?.tags)" plain type="primary"
                 style="margin-right: 8px; margin-top: 8px">{{ tag }}
        </van-tag>
      </template>
    </van-card>
    <van-cell icon="user-o" title="修改个人信息" is-link to="/user/update"/>
    <van-cell icon="friends-o" title="我创建的队伍" is-link to="/user/create/team"/>
    <van-cell icon="friends" title="我加入的队伍" is-link to="/user/join/team"/>
    <van-tabs v-model:active="activeName" @change="onTabChange" style="margin-bottom: 5px">
      <van-tab title="笔记" name="blog"></van-tab>
      <van-tab title="打卡" name="signIn"></van-tab>
      <van-tab title="共同关注" name="common"></van-tab>
      <van-tab title="关注" name="follow"></van-tab>
    </van-tabs>
    <div v-if="activeName === 'blog'" class="scroll-container" @scroll="handleScroll">
      <van-card v-for="bolg in myBlogList" :thumb="bolg.imageUrl" @click="toBlogDetail(bolg.id)">
        <template #title>
          <div style="margin-top: 10px; font-weight: 700">
            {{bolg.title}}
          </div>
        </template>
        <template #desc>
          <van-text-ellipsis :content="bolg.content" style="margin-top: 5px"/>
        </template>
        <template #bottom>
          <van-icon name="good-job-o" size="25"></van-icon>
          {{ bolg.liked }}
          <van-icon style="margin-left: 14px" name="chat-o" size="25"/>
          {{ bolg.comments }}
        </template>
      </van-card>

      <van-empty v-if="!myBlogList || myBlogList.length < 1" style="width: 100%; height: 100%" image="search" description="暂无笔记"/>
    </div>
    <div v-if="activeName === 'signIn'" class="scroll-container" @scroll="handleScroll">
      <div class="sign-in">
        <van-calendar v-model="showCalendar" :poppable="false" :show-confirm="false" :default-date="defaultDate" :min-date="minDate" :max-date="maxDate" :formatter="formatter">
          <template #title>
            <div class="calendar-title">
              签到
              <van-button size="small" @click="sign">签到</van-button>
            </div>
          </template>
        </van-calendar>
        <p>连续签到天数：{{ continuousDays }}</p>
      </div>
    </div>
    <div v-if="activeName === 'common'" class="scroll-container" @scroll="handleScroll">
      <user-card-list :user-list="commonFollowUserList"/>
      <van-empty v-if="!commonFollowUserList || commonFollowUserList.length < 1"  style="width: 100%; height: 100%" image="https://fastly.jsdelivr.net/npm/@vant/assets/custom-empty-image.png" description="暂时没有共同关注用户"/>
    </div>
    <div v-if="activeName === 'follow'" class="scroll-container" @scroll="handleScroll">
      <div class="blog-list" v-if="blogListOfFollowUser" @scroll="onScroll">
        <div class="blog-box" v-for="blog in blogListOfFollowUser" :key="blog.id">
          <div class="blog-img2" @click="toBlogDetail(blog.id)"><img :src="blog.imageUrl" alt=""/></div>
          <div class="blog-title">{{blog.title}}</div>
          <div class="blog-foot">
            <div class="blog-user-icon"><img :src="blog.avatarUrl || 'http://img2.baidu.com/it/u=1217440372,1279017633&fm=253&app=138&f=JPEG?w=800&h=800'" alt=""></div>
            <div class="blog-user-name">{{blog.username}}</div>
            <div class="blog-liked" @click="handlerLike(blog)">
              <svg t="1646634642977" class="icon" viewBox="0 0 1024 1024" version="1.1"
                   xmlns="http://www.w3.org/2000/svg" p-id="2187" width="16" height="16">
                <path
                    d="M160 944c0 8.8-7.2 16-16 16h-32c-26.5 0-48-21.5-48-48V528c0-26.5 21.5-48 48-48h32c8.8 0 16 7.2 16 16v448zM96 416c-53 0-96 43-96 96v416c0 53 43 96 96 96h96c17.7 0 32-14.3 32-32V448c0-17.7-14.3-32-32-32H96zM505.6 64c16.2 0 26.4 8.7 31 13.9 4.6 5.2 12.1 16.3 10.3 32.4l-23.5 203.4c-4.9 42.2 8.6 84.6 36.8 116.4 28.3 31.7 68.9 49.9 111.4 49.9h271.2c6.6 0 10.8 3.3 13.2 6.1s5 7.5 4 14l-48 303.4c-6.9 43.6-29.1 83.4-62.7 112C815.8 944.2 773 960 728.9 960h-317c-33.1 0-59.9-26.8-59.9-59.9v-455c0-6.1 1.7-12 5-17.1 69.5-109 106.4-234.2 107-364h41.6z m0-64h-44.9C427.2 0 400 27.2 400 60.7c0 127.1-39.1 251.2-112 355.3v484.1c0 68.4 55.5 123.9 123.9 123.9h317c122.7 0 227.2-89.3 246.3-210.5l47.9-303.4c7.8-49.4-30.4-94.1-80.4-94.1H671.6c-50.9 0-90.5-44.4-84.6-95l23.5-203.4C617.7 55 568.7 0 505.6 0z"
                    p-id="2188" :fill="blog.isLike ? '#ff6633' : '#82848a'"></path>
              </svg>
              {{blog.liked}}
            </div>
          </div>
        </div>
      </div>
<!--      关注的用户没有发笔记，或没有关注用户-->
      <div v-else>
        <van-empty image-size="100" description="关注用户还没有发布笔记" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {onMounted, ref} from "vue";
import request from "../../plugins/request.ts";
import {useUserStore} from "../../stores";
import {useRouter} from "vue-router";
import {showFailToast} from "vant";
import UserCardList from "../../components/UserCardList.vue";

const userStore = useUserStore()
const router = useRouter()
//存储当前登录用户信息
const currentLoginUser = ref()
const pageNum = ref(1);
// 控制选中的tab标签
const activeName = ref('blog');
// 当前登录用户创建的blog
const myBlogList = ref([])
// 我关注的用户的blog
const blogListOfFollowUser = ref([])
// 共同关注用户列表
const commonFollowUserList = ref([])
// 上一次获取数据截取的时间戳
const minTime = ref(0)
// 获取关注用户的blog的偏移量
const offset = ref(0)

onMounted(async () => {
  const result = await request.get('/user/current')
  if (result.data.data) {
    currentLoginUser.value = result.data.data
    userStore.setCurrentLoginUser(currentLoginUser.value)
  }
  // 查询我的博客
  await queryMyBlog()
})
/**
 * 跳转到博客详情页
 */
const toBlogDetail = (blogId) => {
  router.push({
    path: '/nearby/blog/detail',
    query: {
      blogId
    }
  })
}
/**
 * 实现对关注用户的某个博客的点赞功能，并排序
 */
const handlerLike = async (blog) => {
  //点赞博客
  const result = await request.put("/blog/like/" + blog.id)
  if (result.data.code === 200 && result.data.data) {
    // 点赞成功时，重新查询被点赞的blog
    const res = await request.get("/blog/" + blog.id)
    if (res.data.code === 200 || res.data.data) {
      // this.blog = res.data.data
      blog.liked = res.data.data.liked
      blog.isLike = res.data.data.isLike
    } else {
      showFailToast("重新获取笔记失败" + res.data.message)
      blog.liked++
    }
  } else {
    showFailToast("点赞失败"+ result.data.message)
  }
}
/**
 * 查询我的博客
 */
const queryMyBlog = async () => {
  pageNum.value = 1
  const result = await request.get(`/blog/of/me`, {
    params: {
      current: pageNum.value
    }
  })
  if (result.data.code === 200 && result.data.data) {
    myBlogList.value = result.data.data
  }
}
/**
 * 查询我关注的用户的博客    请求结果得到一个 scrollResult
 * private List<?> list;
 * private Long minTime;
 * private Integer offset; 获取下一页数据的偏移量
 */
const queryBlogsOfFollow = async (isReset: boolean) => {
  if (isReset) {
    offset.value = 0;
    minTime.value = new Date().getTime() + 1
  }
  const result = await request.get("/blog/of/follow", {
    params: {
      lastId: minTime.value ? minTime.value : new Date().getMilliseconds(),
      offset: offset.value ? offset.value : 0
    }
  })
  //获取数据成功
  if (result.data.code === 200 && result.data.data) {
    blogListOfFollowUser.value = result.data.data.list
    // 查询关注用户的博客成功后，后端会返回 获取下一页数据的偏移量，和最小时间戳。这都是用于分页的
    minTime.value = result.data.data.minTime
    offset.value = result.data.data.offset
  }
}
/**
 * tab标签事件
 */
const onTabChange = async (name) => {
  if (name === "blog") {
    await queryMyBlog()
  }
  if (name === "signIn") {
    // 获取连续签到数
    await getSignInCount()
  }
  if (name === "common") {
    await getCommonUser()
  }
  if (name === "follow") {
    // 刚切换到关注用户的blog页，需要从第一条开始获取
    await queryBlogsOfFollow(true)
  }
}
/**
 * 获取共同关注用户的方法
 */
const getCommonUser = async () => {
  const result = await request.get("/follow/common/random")
  if (result.data.code === 200 && result.data.data) {
    result.data.data.forEach((user: any) => {
      if (user.tags) {
        // 将json字符串转换为数组
        user.tags = JSON.parse(user.tags)
      }
    })
    commonFollowUserList.value = result.data.data
  } else {
    showToast({
      message: '暂时没有共同关注用户',
      icon: 'like-o',
    });
  }
}
/**
 * 打卡页面实现
 */
const showCalendar = ref(true);
const continuousDays = ref(parseInt(localStorage.getItem('continuousDays') || '0'));
const signedDates = ref(new Set<string>(JSON.parse(localStorage.getItem('signedDates') || '[]')));
const today = new Date();
const defaultDate = ref(today);
const minDate = ref(new Date(today.getFullYear(), today.getMonth(), today.getDate() - 7));
const maxDate = ref(new Date(today.getFullYear(), today.getMonth(), today.getDate() + 17));

const formatter = (day: any) => {
  const date = `${day.date.getFullYear()}-${day.date.getMonth() + 1}-${day.date.getDate()}`;
  if (signedDates.value.has(date)) {
    day.bottomInfo = '已签到';
    day.className = 'signed-day';
  }
  return day;
};
//签到
const sign = async () => {
  const dateStr = `${today.getFullYear()}-${today.getMonth() + 1}-${today.getDate()}`;
  if (!signedDates.value.has(dateStr)) {
    signedDates.value.add(dateStr);
    continuousDays.value++;
    localStorage.setItem('signedDates', JSON.stringify(Array.from(signedDates.value)));
    localStorage.setItem('continuousDays', continuousDays.value.toString());
  }
  // 向后端发送签到请求
  const result = await request.post("/user/sign")
  if (result.data.code !== 200) {
    showFailToast("签到失败！")
  }
};
// 获取连续签到天数
const getSignInCount = async () => {
  const result = await request.post("/user/sign/count")
  if (result.data.code === 200 && result.data.data) {
    continuousDays.value = result.data.data
  }
}
/**
 * 实现自己笔记页面滚动分页
 */
let flag = false;
async function handleScroll(event: Event) {
  const {target} = event;
  const scrollContainer = target as HTMLElement;
  if (scrollContainer && !flag) { //检查是否在加载中
    const {scrollTop, scrollHeight, clientHeight} = scrollContainer;
    if (scrollTop + clientHeight + 1 >= scrollHeight && activeName.value == "blog") { // 到达底部时加载更多
      flag = true;
      pageNum.value++
      try {
        // 加载数据的函数
        const result = await request.get(`/blog/of/me`, {
          params: {
            current: pageNum.value
          }
        })
        if (result.data.code === 200 && result.data.data) {
          myBlogList.value.push(...result.data.data)
        }
      } catch (error) {
        console.log('error===', error)
      } finally {
        flag = false
      }
    }
  }
}

/**
 * 实现关注用户的blog页滚动
 */
async function onScroll(event: Event) {
  const {target} = event;
  const scrollContainer = target as HTMLElement;
  if (scrollContainer && !flag) { //检查是否在加载中
    const {scrollTop, scrollHeight, clientHeight} = scrollContainer;
    if (scrollTop === 0) {
      //达到顶部，查询一次
      await queryBlogsOfFollow(true)
    }
    if (scrollTop + clientHeight >= scrollHeight) { // 到达底部时加载更多
      // 加载数据的函数 //查询下一页数据
      await queryBlogsOfFollow(false)
    }
  }
}
</script>

<style scoped>
.scroll-container {
  height: 270px; /* 或根据需要调整 */
  overflow-y: auto;
}
.blog-list {
  height: 100%;
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  overflow-y: auto;
  font-size: 12px;
}
.blog-box {
  width: 90%;
  background-color: #ffffff;
  margin: 5px 0;
  box-shadow: 0 3px 4px 1px rgba(0,0,0, 0.1);
  border-radius: 3px;
}
.blog-img2 img {
  width: 100%;
  border-right: 3px;
}

.blog-img img {
  width: 100%;
  height: 100%;
}

.blog-title {
  padding: 2px 10px;
  line-height: 24px;
  width: 92%;
  overflow: hidden;
}
.blog-liked {
  line-height: 16px;
  align-items: center;
}
.blog-liked img {
  width: 16px;
  height: 16px;
}
.blog-comments i {
  font-size: 16px;
}
.blog-foot {
  display: flex;
  justify-content: space-between;
  margin: 10px 0 5px 0;
  padding: 0 10px;
}
.blog-user-icon {
  width: 10%;
  margin-right: 3px;
}
.blog-user-icon img {
  overflow-clip-margin: content-box;
  overflow: clip;
  width: 100%;
  border-radius: 50%;
  margin-right: 3px;
}
.blog-user-name {
  width: 78%;
  overflow: hidden;
}
/*打卡*/
.calendar-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.signed-day .van-calendar-day__content {
  background-color: #4caf50;
  color: white;
}
</style>